<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-card style="margin: 5px 5px 10px 20px">
          <el-text style="font-weight: bold;font-size: 20px">随机组卷</el-text> <br />
          <el-text style="font-weight: bold;font-size: 15px">试题总数:</el-text><br />
          <el-text style="font-weight: bold;font-size: 15px">试卷总分:</el-text><br />
          <el-text style="font-weight: bold;font-size: 15px;color: red">试卷总分必须为100分，否则无法创建试卷</el-text><br />
          <el-button type="primary" style="margin-top: 10px">保存本试卷</el-button>
        </el-card>
      </el-aside>
      <el-main>
        <el-row v-show="showSearch">
          <el-form :model="queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
            <el-form-item label="参与组织" prop="partOrgId">
              <el-cascader v-model="queryForm.partOrgId" ref="cascaderAddr" style="width: 420px" placeholder="请选择标签"
                @change="handleCascaderChange"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }" :options="options1"
                clearable filterable>
              </el-cascader>
            </el-form-item>
            <el-form-item label="专业名称" prop="zymcId">
              <el-select @change="getItem3" v-model="queryForm.zymcId" filterable clearable :required="true">
                <el-option v-for="item in options2" :key="item.zymcId" :label="item.zymcName" :value="item.zymcId" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键点" prop="keyId">
              <el-select @change="getItem2" v-model="queryForm.keyId" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
                <el-option v-for="item in keypointsListData" :key="item.keyId" :label="item.keyPoint"
                  :value="item.keyId" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否随机组卷" prop="isRandom">
              <el-switch v-model="queryForm.isRandom" />
            </el-form-item>
          </el-form>
        </el-row>
        <el-row>
        </el-row>
        <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
          @sort-change="sortChangeHandle">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="questionType" label="题型" show-overflow-tooltip />
          <el-table-column prop="questionNum" label="题目数量" show-overflow-tooltip />
          <el-table-column prop="questionSum" label="题库总数" show-overflow-tooltip />
          <el-table-column prop="mark" label="分值" show-overflow-tooltip />
          <el-table-column prop="markSum" label="总分值" show-overflow-tooltip />
          <el-table-column prop="difficulty" label="难易程度" show-overflow-tooltip />
        </el-table>
        <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />

        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

      </el-main>
    </el-container>
  </div>

</template>

<script setup lang="ts" name="systemKsglExamInfo">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/train/ksglExamInfo";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { ref } from "vue";
import { deptTree, getEditList } from "/@/api/train/kszlData";
import { professionalnameList } from "/@/api/train/jnglProfessionLevel";
import { keypointsList, office, officeView } from "/@/api/train/kszlFile";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
//关键点
const keypointsListData = reactive([{}])
const studyGroupNames = ref([])
const studyGroupIds = ref([])
const queryForm = reactive({
  fileIds: []
})
//学习组织数据
const options1 = ref<any[]>([]);
//专业名称数据
const options2 = reactive([{}])
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)
//挂载完毕
onMounted(() => {
  deptTreeList()
  getProfessionalName()
})
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}
const handleCascaderChange = (item: any) => {
  queryForm.partOrgId = item[item.length - 1]
  // console.log(queryForm.studyGroupId)
  studyGroupIds.value = item
  // console.log(item,'item')
  if (cascaderAddr.value) {
    // console.log('yiji-----',cascaderAddr.value,cascaderAddr.value.getCheckedNodes())
    // 获取选中节点的 pathLabels
    studyGroupNames.value = cascaderAddr.value.getCheckedNodes()[0].pathLabels
    // console.log('Path Labels:', studyGroupNames.value,studyGroupIds.value);
  }
  queryForm.studyGroupIds = studyGroupIds.value
  queryForm.studyGroupNames = studyGroupNames.value
  queryForm.studyPostIds = []
};

// 参与组织
const deptTreeList = () => {
  deptTree().then((res) => {
    options1.value = res.data;
    // console.log("参与组织",options1.value);
    // if(route.query.state=='1'){
    //   if(dataList[0]==undefined){
    //     location.reload()
    //   }
    //   const values = dataList[0].studyGroup.split('/'); // 分割字符串
    //   // console.log('===========',values)
    //   let currentOptions = options1.value; // 当前选项数组
    //   // console.log('//////////',currentOptions)
    //   // 遍历分割后的值，找到匹配的选项并设置到 selectedOptions
    //   values.forEach((value, index) => {
    //     const option = currentOptions.find(item => item.name === value);
    //     // console.log('----------',option.id)
    //     if (option && option.children) {
    //       // 如果找到匹配的选项且它有子选项，则更新 currentOptions 为子选项数组
    //       currentOptions = option.children;
    //     } else {
    //       // 如果没有找到匹配的子选项，则停止遍历
    //       return;
    //     }
    //   })
    //   queryForm.studyGroupId = queryForm.studyGroupId.split('/')
    // }
    // console.log('111、、、',queryForm.studyGroupId.split('/') )
  });
};
//专业名称
const getProfessionalName = () => {
  professionalnameList().then((res) => {
    Object.assign(options2, res.data)
    // console.log("专业名称",options2);
  });
};
const getItem3 = (val: any) => {
  // console.log(val,'11111')
  options2.forEach(item => {
    if (item.zymcId == val) {
      queryForm.zymcName = item.zymcName
    }
  })
  // console.log('queryForm.keyPointIds',queryForm.keyPointIds)
  queryForm.keyId = []
  getKeypointsList()
}
//关键点
const getKeypointsList = () => {
  keypointsListData.length = 0
  const id = queryForm.zymcId
  keypointsList(id).then((res: any) => {
    Object.assign(keypointsListData, res.data)
    // queryForm.dataLevels =  keypointsListData.zydjName
    // queryForm.dataLevelIds =  keypointsListData.zydjId
    // console.log(' queryForm----',  keypointsListData,queryForm)
  });
}
// 导出excel
const exportExcel = () => {
  downBlobFile('/train/ksglExamInfo/export', Object.assign(state.queryForm, { ids: selectObjs }), 'ksglExamInfo.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>